package linuxbox.filelib.servlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;

import linuxbox.BoxStatic;
import linuxbox.common.*;
import linuxbox.filelib.logic.*;

/**
 * <p>Title: Linuxbox</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: </p>
 * @author Xia,Xunfan
 * @version 1.0
 */

public class DownloadFileAction extends Action
{
  protected static Logger logger = Logger.getLogger(DownloadFileAction.class.getName());
  protected static FileLibHome home = FileLibHome.getInstance();

  public void doAction(HttpSession session, BoxSession aBoxSession,
  HttpServletRequest req, HttpServletResponse resp) throws Exception
  {
    logger.debug("Start Download file");
    FileLibEntry entry = null;
    String str = (String) req.getParameter("ID");

    if (str!=null && str.length() > 0)
    {
      int ID = Integer.parseInt(str);
      entry = home.get(ID);
      if (entry.getIsfolder())
        entry = null;
    }
    if (entry == null)
    {
      String msg = "Error to get the file for id:"+str;
      logger.error(msg);
      sendError(msg,req,resp);
      return;
    }

    if (!home.checkAccessRights(aBoxSession.getID(), entry, home.READ_ALLOW))
    {
      logger.warn("Access rights violation for user " + aBoxSession.getLoginID() + " " + entry.getName());
      sendFile(BoxStatic.accessRightErrorJSP,req,resp);
      return;
    }
    String SavedFilename = BoxStatic.HOME_DIR + BoxStatic.DOWNLOAD_FILE_DIR+File.separator + entry.getID();
    File file = new File(SavedFilename);
    if (!file.canRead())
    {
      String msg = "Error to get the file:"+SavedFilename;
      logger.error(msg);
      sendError(msg,req,resp);
      return;
    }

    try
    {
      // Get the output stream
      ServletOutputStream out = resp.getOutputStream();
      // Set the content type and disposition
//    resp.setContentType("application/whatever" + "; name=\"" +filename + "\"");
//    resp.setHeader("Content-Disposition","attachment; filename=" + filename + ";");
      resp.setContentType(entry.getType() + "; name=\"" +entry.getFilename() + "\"");
      resp.setHeader("Content-Disposition","attachment; filename=" + entry.getFilename() + ";");
// Write out your data however you'd like

      BufferedInputStream fif = new BufferedInputStream(new FileInputStream(SavedFilename));
      int data;
      while((data = fif.read()) != -1)
      {
        out.write(data);
      }
      fif.close();
      out.close();
    }
    catch(Exception e)
    {
      String msg = "Error download:" + entry.toString();
      logger.error(msg);
      sendError(msg,req,resp);
    }
  }
}
